import React, { Component } from "react"

export default class Item extends Component {
  state = {
    username: "",
    password: "",
    sex: "",
    hobby: [],
    city: "",
    isAgree: "",
    file: "",
  }
  handle = (name) => (e) => {
    if (e.target.type === "checkbox") {
      const value = e.target.checked
      return this.setState({
        [name]: value,
      })
    } else if (e.target.type === "file") {
      const value = e.target.files[0]
      return this.setState({
        [name]: value,
      })
    } else {
      const value = e.target.value
      return this.setState({
        [name]: value,
      })
    }
  }

  hobbyHandle = (e) => {
    const value = e.target.value
    const index = this.state.hobby.indexOf(value)
    console.log(index);
    if (index > -1) {
      this.state.hobby.splice(index,1)
    } else{
      this.state.hobby.push(value)
    }
    
    this.setState({
      hobby: this.state.hobby,
    })
  }

  render() {
    return (
      <form>
        姓名：
        <input type="text" name="username" onChange={this.handle("username")} />
        <br />
        密码：
        <input
          type="password"
          value={this.state.password}
          onChange={this.handle("password")}
        />
        <br />
        性别：
        <br />
        男：
        <input
          type="radio"
          value="male"
          name="sex"
          onChange={this.handle("sex")}
        />
        女：
        <input
          type="radio"
          value="female"
          name="sex"
          onChange={this.handle("sex")}
        />
        <br />
        爱好：
        <br />
        抽烟：
        <input
          type="checkbox"
          name="hobby"
          value="smoking"
          onChange={this.hobbyHandle}
        />
        喝酒：
        <input
          type="checkbox"
          name="hobby"
          value="drinking"
          onChange={this.hobbyHandle}
        />
        游泳：
        <input
          type="checkbox"
          name="hobby"
          value="swimming"
          onChange={this.hobbyHandle}
        />
        <br />
        城市：
        <select value={this.state.city} onChange={this.handle("city")}>
          <option value="sz">深圳</option>
          <option value="bj">北京</option>
          <option value="sh">上海</option>
        </select>
        <br />
        是否同意：
        <input
          type="checkbox"
          name="isAgree"
          onChange={this.handle("isAgree")}
        />
        <br />
        上传文件：
        <input type="file" onChange={this.handle("file")} />
      </form>
    )
  }
}
